package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.mapper.MessageMapper;
import com.graduation.springbootinit.model.entity.ShopPart.Message;
import com.graduation.springbootinit.service.MessageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message createMessage(Long conversationId, Long senderId, Integer senderType, String content, Integer type) {
        Message message = new Message();
        message.setConversationId(conversationId);
        message.setSenderId(senderId);
        message.setSenderType(senderType);
        message.setContent(content);
        message.setType(type);
        message.setIsRead(false);
        message.setSequence(System.currentTimeMillis());
        
        this.save(message);
        return message;
    }

    @Override
    public List<Message> getHistoryMessages(Long conversationId, Integer limit, Long before) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId);
        if (before != null) {
            wrapper.lt(Message::getId, before);
        }
        wrapper.orderByDesc(Message::getId);
        wrapper.last("LIMIT " + limit);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markMessagesAsRead(Long conversationId, Integer receiverType) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
                .eq(Message::getSenderType, 1 - receiverType)
                .eq(Message::getIsRead, false);
        
        Message updateMessage = new Message();
        updateMessage.setIsRead(true);
        this.update(updateMessage, wrapper);
    }
}